import execjs
import requests, re
# js调用----先获取js文件，复制或自写，再直接调用

def get_sign(word, gtk):
    with open('baidu_translate.js', 'r') as f:
        jscode = f.read()
    ctx = execjs.compile(jscode)
    res = ctx.call('e', word, gtk)
    return res

def get_trans(word):
    session = requests.session()
    session.headers.update({
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    })
    url = 'https://fanyi.baidu.com'
    session.get(url)
    response = session.get(url)
    html = response.text
    token = re.findall(r"token: '(.*?)'", html)[0]
    gtk = re.findall(r"window.gtk = '(.*?)'", html)[0]
    session.post('https://fanyi.baidu.com/langdetect', data={'query': word})
    data = {
        'from': 'en',  # 英翻中文
        'to': 'zh',
        'query': word,
        'transtype': 'realtime',
        'simple_means_flag': 3,
        'sign': get_sign(word, gtk),
        'token': token,
    }
    session.headers.update({
        'referer': 'https://fanyi.baidu.com/?aldtype=16047'
    })
    res = session.post('https://fanyi.baidu.com/v2transapi', data=data).json()
    return res

if __name__ == '__main__':
    word = input('输入要翻译的单词：\t')
    result = get_trans(word)
    print(result['trans_result']['data'][0]['dst'])